IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_ag_showdup_purge]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[usp_ag_showdup_purge]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
	usp_ag_showdup_purge: Eliminate double entries from the #Duplicates temporary table (which needs to be created by the caller)

	Copyright 2010 by Alberto Gemin
	agemin@hotmail.com
	Version 1.0
	30 Jul 2011

	This procedure is called by usp_ag_showdup. Because of the nature of duplicates, if record A is a duplicate of record B, the #Duplicates
	table will have one record reporting that A is a suplicate of B, plus one record reporting that B is a duplicate of A. This procedure
	removes the (somewhat reduntant) second record.

	Note that this is only true when A and B are of the same type. If A and B are of different types (e.g. Contact and Account) only the record
	where A is the base entity is ever inserted in #Duplicates.

*/
CREATE PROCEDURE [dbo].[usp_ag_showdup_purge]
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @BaseEntityTypeCode		INTEGER
	DECLARE @BaseObjectId			UNIQUEIDENTIFIER
	DECLARE @Cursor					CURSOR
	DECLARE @MatchingEntityTypeCode	INTEGER
	DECLARE @MatchingObjectId		UNIQUEIDENTIFIER
	DECLARE @RuleId					UNIQUEIDENTIFIER

	SET @Cursor = CURSOR for
		SELECT
			RuleId,
			BaseEntityTypeCode,
			BaseObjectId,
			MatchingEntityTypeCode,
			MatchingObjectId
		FROM
			#Duplicates

	OPEN @Cursor
	FETCH NEXT FROM @Cursor INTO @RuleId, @BaseEntityTypeCode, @BaseObjectId, @MatchingEntityTypeCode, @MatchingObjectId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		DELETE FROM
			#Duplicates
		WHERE
				MatchingObjectId = @BaseObjectId
			AND BaseObjectId = @MatchingObjectId
			AND MatchingEntityTypeCode = @BaseEntityTypeCode
			AND BaseEntityTypeCode = @MatchingEntityTypeCode

		FETCH NEXT FROM @Cursor INTO @RuleId, @BaseEntityTypeCode, @BaseObjectId, @MatchingEntityTypeCode, @MatchingObjectId
	END
	CLOSE @Cursor
	DEALLOCATE @Cursor

END
GO
